package de.upb.messerschmidt.set;

import java.io.IOException;
import java.util.List;

import javax.jdo.PersistenceManager;
import javax.jdo.Query;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.appengine.api.datastore.Key;

import de.upb.messerschmidt.set.entity.Contact;
import de.upb.messerschmidt.set.entity.Person;
import de.upb.messerschmidt.set.jdo.PMF;
import de.upb.messerschmidt.set.util.Utils;

/**
 * Gets meeting information from 2 users ({@link Person}) via an HttpPost and
 * persists it.
 * 
 * @author Tim Messerschmidt
 * 
 */
public class RegisterMetAtServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		String user = req.getParameter("user");
		String contact = req.getParameter("contact");
		String event = req.getParameter("event");

		if (!(user == null && contact == null && event == null)) {
			addToEvents(user, contact, event, resp);
		}
	}

	@SuppressWarnings("unchecked")
	private void addToEvents(String user, String contact, String event,
			HttpServletResponse resp) throws IOException {
		Person userPerson = null;
		Person contactPerson = null;

		String[] userName = Utils.nameParser(user);
		String[] contactName = Utils.nameParser(contact);

		PersistenceManager pm = PMF.get().getPersistenceManager();

		Query personQuery = pm.newQuery(Person.class);
		personQuery.setFilter("name == nameParam && prename == prenameParam");
		personQuery.declareParameters("String nameParam, String prenameParam");

		List<Person> personList = (List<Person>) personQuery.execute(
				userName[0], userName[1]);

		if (!personList.isEmpty()) {
			userPerson = personList.get(0);
		}

		// List with the contact
		List<Person> contactList = (List<Person>) personQuery.execute(
				contactName[0], contactName[1]);

		if (!contactList.isEmpty()) {
			contactPerson = contactList.get(0);
		}

		List<Key> contactKeys = userPerson.getContacts();

		if (contactPerson != null) {
			for (Key key : contactKeys) {
				Query contactQuery = pm.newQuery(Contact.class);
				contactQuery.setFilter("key == keyParam");
				contactQuery.declareParameters("Key keyParam");
				contactQuery
						.declareImports("import com.google.appengine.api.datastore.Key");

				List<Contact> contacts = (List<Contact>) contactQuery
						.execute(key);

				if (contacts != null) {
					if (!contacts.isEmpty()) {
						for (Contact c : contacts) {
							if (c.getContact().equals(contactPerson.getKey())) {
								c.getMetAt().add(event);
								pm.flush();

								resp.getWriter().println(
										"Event saved successfully");
							}
						}
					}
				}
			}
			pm.close();
		} else {
			pm.close();
			resp.getWriter().println("Couldn't find the Contact");
		}
	}
}
